package com.yundasys.lab08jvm.commonspool;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.sql.*;

/**
 * @PACKAGE_NAME: com.yundasys.lab08jvm.commonspool
 * @NAME: ConnectionPooledObjectFactory
 * @USER: jiangta
 * @DATE: 2021/2/11
 * @TIME: 10:51 下午
 * @PROJECT_NAME: springboot-labs
 */
public class ConnectionPooledObjectFactory implements PooledObjectFactory<MyConnection> {


    @Override
    public PooledObject<MyConnection> makeObject() throws Exception {
                Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://10.172.58.20:3402/heitu?characterEncoding=UTF-8&useSSL=false"
                , "pre", "haJwqnDnS9Qq5ZJCCFxf");
        MyConnection myConnection = new MyConnection();
        myConnection.setConnection(connection);
        return new DefaultPooledObject(myConnection);
    }

    @Override
    public void destroyObject(PooledObject<MyConnection> pooledObject) throws Exception {
        pooledObject.getObject().close();
    }

    @Override
    public boolean validateObject(PooledObject<MyConnection> pooledObject) {
        Connection connection = pooledObject.getObject();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("select 1");
            ResultSet resultSet = preparedStatement.executeQuery();
            int anInt = resultSet.getInt(1);
            return anInt == 1;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

    @Override
    public void activateObject(PooledObject<MyConnection> pooledObject) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<MyConnection> pooledObject) throws Exception {
        //钝化
        MyConnection myConnection = pooledObject.getObject();
        Statement statement = myConnection.getStatement();
        if(statement != null) {
            statement.close();
        }
    }
}
